<template>  <!--该页面为从设备探索进入的历史探索测试记录页面-->
  <div>
    <el-breadcrumb separator="/"> <!--面包屑never-->
    <el-breadcrumb-item><i class="el-icon-s-home" style="margin-right: 15px;font-size: 16px"></i>部门管理</el-breadcrumb-item>
    </el-breadcrumb>
	  <div class="info">
      <!-- 暂无部门管理 -->
      <el-card shadow="always" class="cardPosition">
        <!-- <div slot="header" class="clearfix">
        <el-row align="middle" type="flex"> 
          <div style="margin-right:10px;width: 60px;">
            <span style="align:center" >部门名称</span>
          </div>
          <el-col :span="4">
            <el-row>
              <el-input placeholder="请输入部门名称" clearable v-model="searchContent"  size="small"></el-input>
            </el-row>
          </el-col>
          <el-col :span="18" >
          </el-col>
            <el-button type="primary" @click="toSearchDept"  size="small">查询</el-button>
        </el-row>
        </div> -->
        <div slot="header" class="clearfix">
          <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item class="roleInput" label="部门名称">
              <el-input v-model.trim="formInline.searchContent" placeholder="请输入部门名称" clearable  size="small"></el-input>
            </el-form-item>
            <el-form-item style="float: right;" label="">
              <el-button @click="toSearchDept" style="float: right;" size="small" type="primary">查询</el-button>
            </el-form-item>
          </el-form>
        </div>
      <!-- </el-card>
      <el-card shadow="always" class="cardPosition"> -->
        <el-row>
        <el-button type="text" class="global_add" @click="dialogVisible = true" :disabled="btnList.add" size="small" style="float:right; margin-right: 15px;margin-bottom: 5px;">+&nbsp;新增部门</el-button>
        </el-row>
        <el-dialog
          title="新增部门"
          :visible.sync="dialogVisible"
          width="450px"
          >
          <el-form label-width="120px" :model="newDept" :rules="rules" ref="newDept">
            <el-form-item label="部门名称" prop="deptName">
              <el-input placeholder="请输入部门名称" v-model.trim="newDept.deptName" style="width: 90%" size="small" clearable></el-input>
            </el-form-item>
              <!-- <el-form-item>
                <div style="float: right">
                  <el-button @click="cancel">取消</el-button>
                  <el-button type="primary" @click="submitForm('newDept')">保存</el-button>
                </div>
              </el-form-item> -->
          </el-form> 
          <span slot="footer" class="dialog-footer">
                    <el-button class="textBtn" @click="cancel">取消</el-button>
                  <el-button type="primary" @click="submitForm('newDept')">保存</el-button>
                  </span>
        </el-dialog>
        <el-table stripe v-loading="dataLoading" :data="tableData.slice((currentPage-1)*pagesize,currentPage*pagesize)" border style="width: 100%">
          <el-table-column type="index" label="#" :index = '(index) =>{return (index + 1) + (currentPage - 1) * pagesize}' width="70" align="center"></el-table-column>
          <el-table-column align="center" prop="dept_name" label="部门名称" :span="12"></el-table-column>
          <el-table-column align="center" label="操作"  :span="12">
            <template slot-scope="scope">
              <el-button class="global_edit" @click="toEditDept(scope.$index, scope.row)" type="text" size="small" :disabled="btnList.edit" style="color:#6C59DD">编辑</el-button>
                
              <el-button class="global_delete" type="text" size="small" @click="toDeleteDept(scope.$index, scope.row)" :disabled="btnList.delete" style="color:#D9001B;">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination class="pagination" background :current-page.sync="currentPage" :hide-on-single-page="showPagination" :page-size="pagesize" layout="prev, pager, next" :total="tableData.length"></el-pagination>
      </el-card>
      <el-dialog
                  title="编辑部门"
                  :visible.sync="editDeptdialog"
                  width="450px"
                  >
                  <el-form  label-width="120px" :model="editDept" :rules="rules" ref="editDept">
                    <el-form-item label="部门名称" prop="deptName">
                      <el-input placeholder="请输入部门名称" v-model.trim="editDept.deptName"  style="width: 90%" size="small" clearable></el-input>
                    </el-form-item>
                    <!-- <el-form-item>
                      <div style="float: right">
                        <el-button @click="editDeptdialog = false">取消</el-button>
                        <el-button type="primary" @click="submitEditForm('editDept')">保存</el-button>
                      </div>
                    </el-form-item> -->
                  </el-form> 
                  <span slot="footer" class="dialog-footer">
                    <el-button class="textBtn" @click="editDeptdialog = false">取消</el-button>
                    <el-button type="primary" @click="submitEditForm('editDept')">保存</el-button>
                  </span>
                </el-dialog>
    </div>
  </div>
</template>
<script>
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 引入需要用到的第三方nodejs库，如日期计算等
// 需要先通过npm安装第三方组件包，然后在代码中使用
// npm install xxx :settings="chartSettings"
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
import moment from 'moment';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import roleBtn from '../../public/means'
export default {
	data() {
    
		return {
      formInline: {
        searchContent: '',
      },
      dialogVisible: false,
      editDeptdialog:false,
      showPagination: true,     //分页显示
      currentPage: 1,           //从第几页开始显示
      pagesize: 10,              //每页多少行数据
      dataLoading: false,
      menu_id: 8,
      btnList: {
        add: false,
        edit: false,
        delete: false,
      },
      searchContent:'',
      newDept:{
        deptName:'',
      },
      editDept:{
        deptId:'',
        deptName:'',
      },
      rules:{
        deptName:[
          {required: true, message: '请输入部门名称', trigger: 'blur' },
          {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
        ],
      },
      tableData: [],
      deptlist:[]
		};
	},
	methods: {
    submitForm(formName) {
      this.$message.closeAll();
      let check = true;
      if(this.newDept.deptName=="" ||this.newDept.deptName.length<2||this.newDept.deptName.length>10){
        this.$message({ message: '请输入正确的部门名称！', type: 'error', duration: 1000 });
        check = false;
      }else{
        for(let i = 0;i < this.tableData.length;i++){
          if(this.newDept.deptName == this.tableData[i].dept_name){
            this.$message.closeAll();
            this.$message({ message: '部门名称不可重复！', type: 'error', duration: 1000 });
            check = false;
          }
        }
      }
      if(check)
        this.saveNewDept();
    },
    submitEditForm(formName){
      this.$message.closeAll();
      let check = true;
      if(this.editDept.deptName=="" ||this.editDept.deptName.length<2||this.editDept.deptName.length>10){
        this.$message({ message: '请输入正确的部门名称！', type: 'error', duration: 1000 });
        check = false;
      }else{
        for(let i = 0;i < this.tableData.length;i++){
          if(this.editDept.deptId !== this.tableData[i].dept_id){
            if(this.editDept.deptName == this.tableData[i].dept_name){
            this.$message.closeAll();
            this.$message({ message: '部门名称不可重复！', type: 'error', duration: 1000 });
            check = false;
          }
          }
        }
      }
      if(check)
        this.saveEditDept();
    },
    //搜索
    toSearchDept(){
      this.getAllDept();
    },
    async getAllDept(){
      this.dataLoading = true;
      const params = {
        'searchContent': this.searchContent,
      }
      const ret = await this.$http.get("/deptManagement/getAllDept",{params,});
      this.tableData = ret.result;
      this.dataLoading = false;
      
    },
    //删除部门
    toDeleteDept (index,row){
      this.$confirm('确定删除该部门？,此操作不可撤销', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(({ result }) => {
        if(!result){
					this.deleteDept(row.dept_id,index);
				}
      }).catch(() => {
        });
    },
    //删除部门
    async deleteDept(dept_id,index){
      let ret;
      const params = {
        'dept_id': dept_id,
      }
      ret = await this.$http.delete("/deptManagement/deleteDept",{params,});
      if(ret.code === 200&&ret.message === '删除成功'){
      this.$message({
          showClose: true,
          message: ret.message,
          type: 'success'
        });
        this.$delete(this.tableData, index)
      }
      if(ret.message === '删除失败,该部门存在用户'){
      this.$message({
          showClose: true,
          message: ret.message,
          type: 'warning'
        });
      }
    },
    toEditDept(index,row){
      this.editDeptdialog=true;
      this.editDept.deptId=row.dept_id;
      this.editDept.deptName=row.dept_name;
    } ,
    //修改部门信息
    async saveEditDept(){
      const params = {
        'dept_id': this.editDept.deptId,
        'dept_name': this.editDept.deptName,
      };
      const ret = await this.$http.post("/deptManagement/saveEditDept",params);
        if(ret.code === 200){
        this.$message({
          showClose: true,
          message: '修改成功',
          type: 'success'
        });
      }
  
      this.$refs['editDept'].resetFields();
      this.editDeptdialog = false;
      this.getAllDept();
    },
    //新增部门
    async saveNewDept(){
      const params = {
        'dept_name': this.newDept.deptName,
      };
      const ret = await this.$http.post("/deptManagement/saveNewDept",params);
        if(ret.code === 200){
        this.$message({
          showClose: true,
          message: '添加成功',
          type: 'success'
        });
      }
      this.$refs['newDept'].resetFields();
      this.tableData.splice((this.currentPage-1) * this.pagesize, 0 ,ret.result[0])
      this.dialogVisible = false;
      // this.getAllDept();
    },
    cancel() {
      this.$refs.newDept.resetFields()
      this.dialogVisible = false
    }
  },
	mounted() {
    this.getAllDept();
	},
  async created() {
    const role_id = JSON.parse(sessionStorage.getItem('userInfo')).role_id;
      if(role_id){
      // 获取按钮权限状态
      let arr = await roleBtn.roleBtnList(role_id, this.menu_id)
      this.btnList = arr
    }
  }
};
</script>
<style lang="scss" scoped>
@import "./DeptManagement.scss";
</style>